//
//  Dictionary+YCNetworkingMethods.swift
//  YCNetworking
//
//  Created by YC on 2017/3/6.
//  Copyright © 2017年 YC. All rights reserved.
//

import UIKit

extension Dictionary {
    func YC_urlParamsString(signature: Bool) -> String {
        let sortedArray = self.YC_transformedUrlParamsArray(signature: signature)
        
        var paramString = ""
        for value in sortedArray {
            if paramString.characters.count == 0 {
                paramString.append(value)
            }else {
                paramString.append("&" + value)
            }
        }
        
        return paramString
    }
    
    func YC_jsonString() -> String {
        let jsonData = try! JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
        
        return String(data: jsonData, encoding: .utf8)!
    }
    
    func YC_transformedUrlParamsArray(signature: Bool) -> Array<String> {
        
        var result = [String]()
        
        for (_, obj) in self.enumerated() {
            var value: String
            if (obj.value is String) == false {
                value = "\(obj.value)"
            }else {
                value = obj.value as! String
            }
            
            if !signature {
                value = value.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!$&'()+,-./:;=?@_~%#[]"))!
            }
            
            if value.characters.count > 0 {
                result.append("\(obj.key)"+value)
            }
        }
        
        result.sort(by: <)
        
        return result
    }
}
